package com.blue.integration.serve.netpopo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blue.core.http.HttpException;
import com.blue.core.util.FileUtil;
import com.blue.core.util.JsonUtil;
import com.blue.integration.serve.LicensePlate;
import com.blue.integration.serve.OcrException;
import com.blue.integration.serve.PlateClient;
import com.blue.integration.serve.aliyun.AbstractOcrClient;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 阿里云OCR车牌识别接口
 *
 * @author zhengjin
 * @since 1.0 2017年11月28日
 */
public class NetpopoPlateClient extends AbstractOcrClient implements PlateClient
{
	private static Logger logger = LoggerFactory.getLogger(NetpopoPlateClient.class);

	public NetpopoPlateClient()
	{
	}

	@Override
	public LicensePlate ocr(File file) throws OcrException
	{
		Assert.notNull(file, "车牌文件不能为空");
		try
		{
			FileInputStream fis = new FileInputStream(file);
			return this.ocr(fis);
		}
		catch (FileNotFoundException e)
		{
			throw new OcrException("车牌文件不存在：" + file.getAbsolutePath());
		}
	}

	@Override
	public LicensePlate ocr(InputStream is) throws OcrException
	{
		Assert.notNull(is, "车牌号文件输入流不能为空");

		String imgBase64 = null;
		try
		{
			imgBase64 = FileUtil.toBase64(is);
		}
		catch (IOException e)
		{
			logger.error("读取车牌号文件失败：", e);
			throw new OcrException("读取车牌号文件失败");
		}
		if (imgBase64 == null || imgBase64.isEmpty())
			throw new OcrException("读取车牌号文件失败");

		Header authHeader = new BasicHeader("Authorization", "APPCODE " + appCode);
		Header contentTypeHeader = new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

		Map<String, Object> param = new HashMap<>();
		param.put("pic", imgBase64);
		String result = null;
		try
		{
			logger.debug("参数：{}", param);
			result = httpInvoker.post(url, param, authHeader, contentTypeHeader);
			logger.info("结果：{}", result);
		}
		catch (HttpException | IOException e)
		{
			logger.error("车牌号识别失败：", e);
			throw new OcrException("车牌号识别失败");
		}
		if (result == null || result.isEmpty())
			throw new OcrException("车牌号识别失败");

		JSONObject rootObj = JSON.parseObject(result);
		String status = rootObj.getString("status");
		if (!"0".equals(status))
			throw new OcrException("车牌号识别失败，原因：" + rootObj.getString("msg"));

		NetpopoLicensePlate aliyunPate = rootObj.getObject("result", NetpopoLicensePlate.class);
		logger.debug("对象：{}", JsonUtil.encode(aliyunPate));

		LicensePlate plate = aliyunPate.toLicensePlate();
		return plate;
	}

	@Override
	public void afterPropertiesSet() throws Exception
	{
		super.afterPropertiesSet();

		logger.info("初始化阿里云OCR车牌识别接口：{}", url);
	}
}
